﻿package com.mirror.utils.xml;

import android.util.Log;

import com.mirror.llk.bean.response.BaseResponse;
import com.mirror.llk.utils.Interface;
import com.thoughtworks.xstream.XStream;

/**
 * @Title: XStream 工具 接口输入输出参数 XML与BEAN转换 XML的解析支撑类
 * @Copyright: Copyright (c) 2012-7-30
 * @Company: 幻方朗睿
 * @Author: Andy.D
 * @Version: 1.0
 */
public final class XStreamUtils {

	/** HTTP相应头部 */
	public static final String XML_HEAD = "<?xml version='1.0' encoding='UTF-8'?>";

	private static final String TAG = "XStreamUtils";

	/**
	 * <默认构造函数>
	 */
	private XStreamUtils() {
	}

	/**
	 * xml类型转换成Object类型
	 * 
	 * @param xml
	 * @param objClass
	 * @return 转换后的对象
	 */
	public static Object parseXmlToObj(String xml, Class<?> objClass) {
		if (Interface.ERROR_CODE.contains(xml)) {
			return new BaseResponse(xml, Interface.ERROR_MESSAGE.get(xml));
		}
		Object obj = null;
		try {
			XStream xstream = new XStream();
			// 显示声明使用注解
			xstream.processAnnotations(objClass);
			xstream.autodetectAnnotations(true);
			obj = xstream.fromXML(xml);
		}
		catch (Exception e) {
			return new BaseResponse(Interface.ERROR_CODE_9998, Interface.ERROR_MESSAGE.get(Interface.ERROR_CODE_9998));
		}
		return obj;
	}

	/**
	 * Object类型转换成xml
	 * 
	 * @param out
	 * @return String 输入xml
	 */
	public static String parseObjToXml(Object out) {
		String str = null;
		try {
			XStream xstream = new XStream();
			// 显示声明使用注解
			xstream.processAnnotations(out.getClass());
			xstream.autodetectAnnotations(true);
			str = xstream.toXML(out);
			str = XML_HEAD + str;
		}
		catch (Exception e) {
			Log.e(TAG, "parseObjToXml异常", e);
		}
		return str;
	}
}